import {defineStore} from 'pinia'
import { ref,watch} from 'vue'

const STORAGE_KEY = 'user_login_info'

export const useUserStore = defineStore('user', ()=> {
    const isLoggedIn = ref(false)
    const username = ref('')
    const role = ref('')

    const loadUserFromStorage = () => {
        const storedData = localStorage.getItem(STORAGE_KEY)
        if(storedData){
            const user = JSON.parse(storedData)
            isLoggedIn.value = user.isLoggedIn
            username.value = user.username
            role.value = user.role
        }
    }

    const login = (user) =>{
        isLoggedIn.value = true
        username.value = user.username
        role.value = user.role

        localStorage.setItem(
            STORAGE_KEY,
            JSON.stringify({isLoggedIn: true, username:user.username,role: user.role}))
    }

    const logout = () => {
        isLoggedIn.value = false
        username.value = ''
        role.value = ''

        localStorage.removeItem(STORAGE_KEY)
    }

    watch(
        [isLoggedIn, username, role],
        () => {
            if(isLoggedIn.value){
                localStorage.setItem(
                    STORAGE_KEY,
                    JSON.stringify({isLoggedIn: isLoggedIn.value, username: username.value, role: role.value})
                )
            }
        },
        { deep: true }
    )

    loadUserFromStorage()

    return {isLoggedIn, username, role, login, logout}
})